<template>
    <div 
        ref="AutoMoveList"
        class="auto-move-list"
        :style="{
            '--my-list-gap':listGap+'px',
        }">
        <div 
            ref="AutoMoveListContainer"
            class="auto-move-list-container"
            :style="{
                'gridTemplateColumns': `repeat(${dataList.length}, max-content)`,
            }">
            <div 
                class="auto-move-list-item"
                v-for="(item,index) in dataList"
                :key="index">
                <slot :itemData="item"></slot>
            </div>
        </div>
        <div
            class="auto-move-list-container"
            :style="{
                'gridTemplateColumns': `repeat(${dataList.length}, max-content)`,
            }">
            <div 
                class="auto-move-list-item"
                v-for="(item,index) in dataList"
                :key="index">
                <slot :itemData="item"></slot>
            </div>
        </div>
    </div>
</template>

<script>
/*
 水平自动移动列表组件
 */
import {TaskControl} from '@/common/SimpleAnimation';
const taskServe = new TaskControl();
export default {
    name: 'AutoMoveList',
    props:{
        dataList:{
            type: Array,
            default: () => {
                return [];
            },
        },
        speed:{  //移动速度
            type:Number,
            default:0.1,
        },
        listGap:{  //间距
            type:Number,
            default:10,
        },
    },
    data() {
        this.timer = undefined;
        return {};
    },
    mounted(){
        this.startMove();
    },
    methods: {
        isActive(){  //是否是当前活动的组件
            const el = this.$el;
            if(!el) return false;
            return !!(el.clientWidth || el.clientHeight);
        },
        startMove(){  //开始移动
            let el = this.$refs.AutoMoveList;
            let el1 = this.$refs.AutoMoveListContainer;
            let x = 0;
            let await_ = false;
            this.timer = taskServe.add(()=>{
                if(await_) return;
                if(!this.isActive()) return;
                x += this.speed;
                el.style.transform = `translateX(${-x}px)`;
                let el1Data = el1.getBoundingClientRect();
                if(x>=el1Data.width+this.listGap){
                    x = 0;
                }
            });
            //添加hove事件
            el.addEventListener('mouseover',()=>{
                await_ = true;
            });
            el.addEventListener('mouseout',()=>{
                await_ = false;
            });
        },
    },
    destroyed(){
        taskServe.clear(this.timer);
    },
}
</script>

<style scoped lang="scss">
.auto-move-list{
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: var(--my-list-gap);
    width: fit-content;
    >.auto-move-list-container{
        display: grid;
        grid-gap: var(--my-list-gap);
    }
}
</style>
